using System;
using BitBenderGames;
using UnityEngine;

namespace WorldMap.TouchCamera
{
    public class WorldMapCameraComponent : CameraComponent
    {
        public Camera HudCamera;
        public bool isUpdatenearClip = true;

        public Material[] materials;
        
        private bool _enableAutoDepthOffset = false;
        private bool _isChange = false;

        private void Start()
        {
            for (int i = 0; i < materials.Length; i++)
            {
                materials[i].DisableKeyword("_AUTODEPTHOFFSET");
                //UnityEngine.Debug.LogError("默认关闭_AUTODEPTHOFFSET");
            }
        }

        public override void OnLateUpdate()
        {
            float zoom = Mathf.Sqrt(2) * cameraController.CameraTransform.position.y;
            cameraController.Camera.farClipPlane = zoom * 2.5f;

            HudCamera.farClipPlane = zoom * 2.5f;
            if (isUpdatenearClip)
            {
                cameraController.Camera.nearClipPlane = zoom * 0.4f;
                HudCamera.nearClipPlane = zoom * 0.4f;
            }
            
            //相机拉远时远距离位置的沙盘HUD深度精度过低，为了避免出现HUD之间交叉闪烁的情况，根据当前远裁剪面的值动态调整shader中的速度偏移值。
            _enableAutoDepthOffset = HudCamera.farClipPlane > 90.0f ? true : false;
            if (_enableAutoDepthOffset)
            {
                if (materials.Length == 0)
                {
                    //UnityEngine.Debug.LogError("材质为空！");
                    return;
                }
                
                if (!materials[0].IsKeywordEnabled("_AUTODEPTHOFFSET"))
                {
                    for (int i = 0; i < materials.Length; i++)
                    {
                        materials[i].EnableKeyword("_AUTODEPTHOFFSET");
                        _isChange = true;
                        //UnityEngine.Debug.LogError("开启_AUTODEPTHOFFSET" + "____isChange:" + _isChange);
                    }
                }
                
                Shader.SetGlobalFloat("_CameraFarClipValue",HudCamera.farClipPlane);
                //UnityEngine.Debug.LogWarning("_CameraFarClipValue:" + HudCamera.farClipPlane);
                //UnityEngine.Debug.LogError("LERP:" + Mathf.Lerp(-12,-36,(HudCamera.farClipPlane - 90)/(2500 - 90)) + "LERP_X:" + (HudCamera.farClipPlane - 90)/(2500 - 90));
            }
            else
            {
                if (_isChange)
                {
                    for (int i = 0; i < materials.Length; i++)
                    {
                        materials[i].DisableKeyword("_AUTODEPTHOFFSET");
                        //UnityEngine.Debug.LogError("关闭_AUTODEPTHOFFSET");
                    }
                    _isChange = false;
                    //UnityEngine.Debug.LogError( "____isChange:" + _isChange);
                }
            }
        }
    }
}